﻿using System;
using System.Configuration;
using System.Data;
using System.IO;
using System.Runtime.InteropServices;
using System.Web;
using Library.Tools;

namespace DataObject.Helpers
{
    public class Helper
    {
        private const int RpcSOk = 0;

        [DllImport("rpcrt4.dll", SetLastError = true)]
        private static extern int UuidCreateSequential(out Guid guid);

        /// <summary>
        ///     Generate a new sequential GUID. If UuidCreateSequential fails, it will fall back on standard random guids.
        /// </summary>
        /// <returns>A GUID</returns>
        public static Guid NewSeqGuid()
        {
            Guid sequentialGuid;
            int hResult = UuidCreateSequential(out sequentialGuid);
            if (hResult == RpcSOk)
            {
                return sequentialGuid;
            }
            //couldn't create sequential guid, fall back on random guid
            return Guid.NewGuid();
        }

        /// <summary>
        ///     Read template
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string ReadTemplateFile(string filePath)
        {
            string tempReadTemplate = String.Empty;
            if (File.Exists(filePath))
            {
                StreamReader objStreamReader = File.OpenText(filePath);
                string contents = objStreamReader.ReadToEnd();
                objStreamReader.Close();
                tempReadTemplate = contents;
            }
            return tempReadTemplate;
        }

        /// <summary>
        ///     Read template
        /// </summary>
        /// <returns></returns>
        public static void ReadConfigSMTP(out string displayName, out string host, out int port, out string emailAddress,
            out string password, out bool enableSsl)
        {
            /***** Read SMTP config file *****/
            DataTable dtConfig =
                new IO().RegexToDataTable(
                    HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["SMTP_CONFIG_FILE_PRODUCTION"]));
            DataRow configRow = dtConfig.Rows[(new Random()).Next(dtConfig.Rows.Count)];

            enableSsl = !String.IsNullOrEmpty(configRow.Field<string>("SMTP.UseSSL").Trim()) && Boolean.Parse(configRow.Field<string>("SMTP.UseSSL").Trim());
            port = !String.IsNullOrEmpty(configRow.Field<string>("SMTP.Port").Trim())
                ? Int32.Parse(configRow.Field<string>("SMTP.Port").Trim())
                : 0;
            host = configRow.Field<string>("SMTP.Server").Trim();
            displayName = configRow.Field<string>("SMTP.DisplayName").Trim();
            emailAddress = configRow.Field<string>("SMTP.Username").Trim();
            password = configRow.Field<string>("SMTP.Password").Trim();
        }
    }
}